<template>
  <div>
    <slot>
      <el-input v-model="initDisplayData" :readonly="true" :disabled="true" class="tl-ref-selector" :class="{ disabled: disabled }" v-if="isDisplayDefaultElement">
        <el-button slot="append" icon="el-icon-search" @click="openRefDialog" :disabled="disabled"></el-button>
      </el-input>
    </slot>
    <el-dialog :visible.sync="refVisible" ref="refDailog" :title="refTitle" v-dialogDrag width="1000px" top="52px" :modal-append-to-body="false" :append-to-body="true" class="tl-ref tl-dialog tl-ref-boardroom-item" @open="open" @close="close">
      <div style="position:relative;" v-if="!meetRoomType">
        <el-button icon="el-icon-plus" style="position: absolute;top: -58px;right: 40px;" :type="'text'" @click="openAddDialog">友情提示：您可以创建自己部门的专属会议室</el-button>
      </div>
      <el-row>
        <h4>预约要求</h4>
        <el-form ref="form" class="board-item-filter" :model="requireModel" size="small" label-width="68px" style="padding-right:17px;">
          <el-row>
            <el-col :span="5">
              <el-form-item label="开始时间" prop="begintimeDate">
                <el-date-picker v-model="requireModel.begintimeDate" type="date" placeholder="开始时间" value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="" label-width="2px" prop="begintimeTime">
                <el-time-select
                  v-model="requireModel.begintimeTime"
                  @change="changeBegintimeTime"
                  placeholder="选择时间"
                  editable
                  :picker-options="{
                    start: '00:00',
                    step: '00:05',
                    end: '24:00'
                  }"
                >
                </el-time-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="结束时间" prop="endtimeDate">
                <el-date-picker v-model="requireModel.endtimeDate" type="date" placeholder="结束时间" value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="" label-width="2px" prop="endtimeTime">
                <el-time-select
                  v-model="requireModel.endtimeTime"
                  @change="endtimeChangeNoMore = true"
                  placeholder="选择时间"
                  editable
                  :picker-options="{
                    start: '00:00',
                    step: '00:05',
                    end: '24:00'
                  }"
                >
                </el-time-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="参会人数" prop="count">
                <el-input v-model.number="requireModel.count" controls-position="right" :min="1" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-row>
      <el-row>
        <el-row v-loading="isLoading">
          <el-col :span="8" v-for="item in filterItem" :key="item.id">
            <el-card class="box-card-boardroom-item" shadow="hover">
              <div slot="header" class="clearfix">
                <div class="boardroom-title ellipsis" :title="item.showname + '(' + item.locationdesc + ')'">{{ item.showname + '(' + item.locationdesc + ')' }}</div>
                <div class="control">
                  <el-button type="text" @click="doSelectMeetRoom(item)" :disabled="item.state === -1">选择</el-button>
                  <el-tag :type="itemTagColor(item.state)" size="mini">{{ item.description }}</el-tag>
                  <span v-if="item.uploadedpicture" @click="displayPictureDialog(item.id)" class="view-picture">
                    <el-tooltip placement="top">
                      <div slot="content">会议室图片</div>
                      <i class="el-icon-picture-outline" style="font-size: 15px; color: #0a6ed2; margin-top: 4px" />
                    </el-tooltip>
                  </span>
                </div>
              </div>
              <div class="ellipsis"><i>可承载人数：</i>{{ item.capacity }} 人</div>
              <div class="ellipsis" :title="item.telephone"><i>负责人：</i>{{ item.username + '(' + item.usercode + ')' }} - {{ item.telephone }}</div>
              <div>
                <i>近期预约记录：</i>
                <el-popover placement="top" width="330" trigger="hover" :disabled="!item.applylist || item.applylist.length === 0">
                  <ul class="text item">
                    <li v-for="apply in item.applylist" :key="apply.id">
                      <p>{{ apply.begintime | toDateTime('yyyy-MM-dd HH:mm') }} 至 {{ apply.endtime | toDateTime('yyyy-MM-dd HH:mm') }}</p>
                      <i>会议主题：</i>{{ apply.name }} <br /><i>申请人：</i>{{ apply.username }} ，<i>联系电话：</i>{{ apply.telephone }}
                    </li>
                  </ul>
                  <div slot="reference" class="order-count">{{ item.applylist ? item.applylist.length : 0 }} <svg-icon icon-class="search" v-if="item.applylist" /></div>
                </el-popover>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-row>
      <div slot="footer" class="dialog-footer" v-show="sourceType === 'meetManage'">
        <el-button type="primary" @click="clearSelectRoom">清除选择</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="displayPicture" :title="pictureTitle" :close-on-click-modal="false" top="10px" width="1000px" v-dialogDrag class="tl-dialog" @open="openPictureDialog" @close="closePictureDialog" :append-to-body="true" :modal-append-to-body="true">
      <upload-comp ref="attachment" sourceType="meetRoom" :sourceId="roomId" limitType="jpg;png" :limitSize="102400" :editable="false"></upload-comp>
      <div slot="footer" class="dialog-footer" style="text-align:right;">
        <el-button type="primary" @click="previewVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <tl-edit ref="editForm" @refresh="doRefresh" meetRoomType="dept"></tl-edit>
  </div>
</template>
<script>
/** 子组件 */
import tlEdit from '../meetRoomManage/edit'
import uploadComp from '../meetRecord/uploadComp'
import { putAction, getAction, postAction } from '@tapui/utils/http'
export default {
  name: 'meetRoomList',
  components: { uploadComp, tlEdit },
  data() {
    return {
      refVisible: false,
      dataList: [],
      isLoading: false,
      url: {
        queryMeetRoomWithAvailableList: 'meet/roomManage/queryMeetRoomWithAvailableList',
        queryBoardroomSourceList: '/toa/boardroomSource/list'
      },
      // 会议室资源可选列表
      allSourceList: [],
      displayData: '',
      defaultShowCount: 10,
      displayPicture: false,
      pictureTitle: '会议室图片',
      roomId: 0,
      endtimeChangeNoMore: false
    }
  },
  props: {
    requireModel: {
      default: function() {
        return {
          begintime: '',
          endtime: '',
          count: 0,
          sourcelist: []
        }
      },
      type: Object
    },
    singleSelect: {
      default: true,
      type: Boolean
    },
    dataType: {
      default: 'id',
      type: String
    },
    value: {
      default: '',
      type: [String, Number]
    },
    initDisplayData: {
      default: '',
      type: String
    },
    isDisplayDefaultElement: {
      default: true,
      type: Boolean
    },
    refTitle: {
      default: '选择会议室',
      type: String
    },
    disabled: {
      default: false,
      type: Boolean
    },
    meetRoomType: {
      default: '',
      type: String
    },
    sourceType: {
      default: 'roomApply',
      type: String
    },
    currentRecord: {
      default: function() {
        return {}
      },
      type: Object
    }
  },
  computed: {
    /** 会议室数据计算属性 */
    filterItem() {
      let begintime = new Date(`${this.requireModel.begintimeDate} ${this.requireModel.begintimeTime}`)
      let endtime = new Date(`${this.requireModel.endtimeDate} ${this.requireModel.endtimeTime}`)
      for (let item of this.dataList) {
        item.state = 1 // 1为正常
        item.description = '可选'
        // 判断参会人数是否超过会议室承载量
        if (this.requireModel.count && item.capacity < this.requireModel.count) {
          item.state = 0 // 0为警告
          item.description = '人数超限'
          item.message = '该会议室人数超限, 是否要选择?'
        }
        // 根据预约记录进行计算是否冲突
        if (item.applylist && item.applylist.length > 0) {
          for (let apply of item.applylist) {
            // 如果是当前会议室申请记录则不视为冲突
            if (this.currentRecord.id === apply.id) {
              continue
            }
            let applyBegintime = new Date(apply.begintime)
            let applyEndtime = new Date(apply.endtime)

            let collisionBeginTime = new Date(begintime).setMinutes(begintime.getMinutes() - 30)
            let collisionEndTime = new Date(endtime).setMinutes(endtime.getMinutes() + 30)
            if (applyBegintime && applyEndtime) {
              if (begintime < applyEndtime && endtime > applyBegintime) {
                item.state = -1 // -1为不可选择
                item.description = '时间冲突'
                break
              } else if (begintime > applyBegintime && begintime < applyEndtime) {
                item.state = -1 // -1为不可选择
                item.description = '时间冲突'
                break
              } else if (endtime > applyBegintime && endtime < applyEndtime) {
                item.state = -1 // -1为不可选择
                item.description = '时间冲突'
                break
              } else if ((applyBegintime <= collisionBeginTime && applyEndtime >= collisionBeginTime) || (applyBegintime <= collisionEndTime && applyEndtime >= collisionBeginTime)) {
                item.state = 0
                item.description = '可用'
                item.message = '您预约会议室的起止时间与他人预约会议的起止时间间隔≤30min，可能会因会议延长导致冲突，请确认是否继续预约？'
              }
            }
          }
          // 最多显示10条
          if (item.applylist.length > this.defaultShowCount) {
            item.applylist = item.applylist.splice(0, this.defaultShowCount)
          }
        }
      }
      return this.dataList
    },
    itemTagColor() {
      return function(state) {
        if (state === 1) {
          return 'success'
        } else if (state === 0) {
          return 'warning'
        } else {
          return 'danger'
        }
      }
    }
  },
  methods: {
    changeBegintimeTime() {
      if (!this.endtimeChangeNoMore) {
        let begindate = new Date(`${this.requireModel.begintimeDate} ${this.requireModel.begintimeTime}`)
        // 加9 是因为ISO默认时区为UTC+0  需要utc+8 +1
        let enddate = new Date(begindate.setHours(begindate.getHours() + 9))
        this.requireModel.endtimeDate = enddate.toISOString().substring(0, 10)
        this.requireModel.endtimeTime = enddate.toISOString().substring(11, 16)
      }
    },
    /** 打开界面 */
    open() {
      // 查询会议室，包括会议时间段内内的预约记录
      this.queryMeetRoomList()
      this.$emit('openRoom')
    },
    resetPage() {
      this.endtimeChangeNoMore = false
    },
    close() {
      this.resetPage()
      this.$emit('closeRoom')
    },
    /** 查询会议室和预约记录 */
    queryMeetRoomList() {
      this.isLoading = true
      getAction(this.url.queryMeetRoomWithAvailableList, { qry_meetroomtype: this.meetRoomType })
        .then(res => {
          if (res.success) {
            this.dataList = res.result.dataList
          } else {
            this.$message.warning(res.message)
          }
          this.isLoading = false
        })
        .catch(err => {
          this.isLoading = false
        })
    },
    doCancelEdit() {
      this.refVisible = false
    },
    /** 选择会议室 */
    doSelectMeetRoom(item) {
      let begintime = `${this.requireModel.begintimeDate} ${this.requireModel.begintimeTime}`
      let endtime = `${this.requireModel.endtimeDate} ${this.requireModel.endtimeTime}`
      if (new Date(endtime) <= new Date(begintime)) {
        this.$tap.alert('会议结束时间不能早于会议开始时间！')
        return
      }
      if (item.state === -1) {
        this.$alert('该会议室' + item.description + '，不可选择', '错误', {
          dangerouslyUseHTMLString: true,
          type: 'error'
        })
        return
      }
      if (item.state === 0) {
        this.$confirm(item.message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.doConfirm(item)
          })
          .catch(() => {})
      } else {
        this.doConfirm(item)
      }
    },
    /** 选择会议室确认 */
    doConfirm(item) {
      this.displayData = ''
      let returnData = ''
      returnData = item[this.dataType]
      this.displayData = item.name + '(' + item.locationdesc + ')'
      this.$set(this.requireModel, 'meetroomtype', item.type)
      this.$emit('update:initDisplayData', this.displayData)
      this.$emit('update:requireModel', this.requireModel)
      this.$emit('input', returnData)
      this.$emit('confirm', item)
      this.$emit('updateRequire', this.requireModel)
      this.refVisible = false
    },
    /** 打开界面 */
    openRefDialog() {
      if (this.disabled) {
        return
      }
      this.$emit('open')
      this.refVisible = true
    },
    // 清楚选择的会议室
    clearSelectRoom() {
      this.$emit('clearRoom')
      this.refVisible = false
    },
    openPictureDialog() {
      this.$nextTick(_ => {
        this.$refs.attachment.loadData()
      })
    },
    closePictureDialog() {
      this.displayPicture = false
    },
    // 显示会议室图片
    displayPictureDialog(id) {
      this.roomId = id
      this.displayPicture = true
    },
    // 打开部门会议室新增页面
    openAddDialog() {
      this.refVisible = false
      this.$refs.editForm.isAdd = true
      this.$refs.editForm.visible = true
      this.$refs.editForm.disableEditSubmit = false
    },
    doRefresh() {}
  },
  created() {}
}
</script>
<style lang="scss">
.tl-ref-boardroom-item {
  .el-dialog__body {
    padding: 15px;
    h4 {
      margin: 0 0 10px 0;
    }
  }
}
.board-item-filter {
  .el-date-editor.el-input {
    width: 190px;
  }
}
.box-card-boardroom-item {
  margin: 5px;
  .el-card__header,
  .el-card__body {
    padding: 10px;
    position: relative;
    & > div {
      line-height: 22px;
    }
    i {
      font-style: normal;
      color: #999;
    }
    .boardroom-title {
      margin-right: 90px;
    }
    .control {
      position: absolute;
      right: 10px;
      top: 10px;
    }
  }
  .el-card__header {
    font-size: 13px;
    .el-tag {
      float: right;
      margin-right: 5px;
      margin-top: 1px;
    }
    .el-button {
      float: right;
      padding: 3px 0;
    }
  }
}
.red {
  color: red;
}
.el-popover {
  i {
    font-style: normal;
    color: #999;
  }
  .text {
    padding: 0;
    margin: 0;
    overflow: hidden;
    li {
      list-style: none;
      padding: 0;
      margin: 0;
      border-bottom: 1px dashed #ccc;
      padding-bottom: 5px;
      margin-bottom: 5px;
      p {
        margin: 0;
      }
    }
  }
}
.order-count {
  display: inline-block;
  font-weight: bold;
}
.view-picture {
  margin-right: 5px;
}
.view-picture:hover {
  cursor: pointer;
}
</style>
